<?php
Loader::import('pspframework.utils.reader.ConfigReaderInterface');
class IniReader implements ConfigReaderInterface {


	protected $_path;


	protected $_section;


	public function __construct($path, $section = null) {
		$this->_path = $path;
		$this->_section = $section;
	}

	function read($file) {
	    $fileName = $this->_path . DS . $file;
		$fileLineArray = file($fileName);
		foreach ($fileLineArray as $fileLine) {
			$dataLine = trim($fileLine);
			$firstChar = substr($dataLine, 0, 1);

			if ($firstChar != ';' && $dataLine != '') {
				if ($firstChar == '[' && substr($dataLine, -1, 1) == ']') {
					$sectionName = preg_replace('/[\[\]]/', '', $dataLine);
				} else {
					$delimiter = strpos($dataLine, '=');

					if ($delimiter > 0) {
						$key = strtolower(trim(substr($dataLine, 0, $delimiter)));
						$value = trim(substr($dataLine, $delimiter + 1));

						if (substr($value, 0, 1) == '"' && substr($value, -1) == '"') {
							$value = substr($value, 1, -1);
						}
                        if(isset($iniSetting[$sectionName][$key]) && !empty($iniSetting[$sectionName][$key])) {
						    $iniSetting[$sectionName][$key] .=stripcslashes($value);						
						}else {
						    $iniSetting[$sectionName][$key]=stripcslashes($value);
						}
						
					} else {
						if (!isset($sectionName)) {
							$sectionName = '';
						}
						$iniSetting[$sectionName][strtolower(trim($dataLine))]='';
					}
				}
			}
		}

		return $iniSetting;
	}	
	


	public function dump($filename, $data) {
		$result = array();
		foreach ($data as $key => $value) {
			if ($key[0] != '[') {
				$result[] = "[$key]";
			}
			if (is_array($value)) {
				$keyValues = $this->flatten($value, '.');
				foreach ($keyValues as $k => $v) {
					$result[] = "$k = " . $this->_value($v);
				}
			}
		}
		$contents = join("\n", $result);
		return file_put_contents($this->_path .DS . $filename, $contents);
	}
	
	protected function _value($val) {
		if ($val === null) {
			return 'null';
		}
		if ($val === true) {
			return 'true';
		}
		if ($val === false) {
			return 'false';
		}
		return (string)$val;
	}
	
	protected function flatten(array $data, $separator = '.') {
		$result = array();
		$stack = array();
		$path = null;

		reset($data);
		while (!empty($data)) {
			$key = key($data);
			$element = $data[$key];
			unset($data[$key]);

			if (is_array($element)) {
				if (!empty($data)) {
					$stack[] = array($data, $path);
				}
				$data = $element;
				$path .= $key . $separator;
			} else {
				$result[$path . $key] = $element;
			}

			if (empty($data) && !empty($stack)) {
				list($data, $path) = array_pop($stack);
			}
		}
		return $result;
	}		
}
?>